/**
 * ContactInfomationServiceImpl.java
 * @author
 * 作者 屈甲康 
 */
package org.jackysoft.service.impl;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.hibernate.Criteria;
import org.hibernate.criterion.Property;
import org.jackysoft.entity.ContractClient;
import org.jackysoft.service.AbstractServiceImpl;
import org.jackysoft.service.ContractClientService;
import org.jackysoft.util.ExcelUtil;
import org.jackysoft.util.IOUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;

@Service
@Transactional
public class ContractClientServiceImpl extends
		AbstractServiceImpl<String, ContractClient> implements
		ContractClientService {
	/**
	 * 
	 */
	private static final long serialVersionUID = -5613981570179242311L;

	public ContractClientServiceImpl() {
	    super(ContractClient.class);
	}

	
	
	@Override	
	@SuppressWarnings("rawtypes")
	public ContractClient getByName(String name) throws DataAccessException {
		Criteria cri = getSession().createCriteria(getType());
		cri.add(Property.forName("name").eq(StringUtils.trim(name)));
		Object obj = null;
		Iterator itr = cri.list().iterator();
		obj = itr.hasNext() ? itr.next() : null;
		return (ContractClient) obj;

	}



	@Override
	public void create(File file, String name) throws Exception {
		byte[] data  = IOUtils.toByteArray(file);
		batchImport(data);
	}



	@Override
	public Collection<ContractClient> batchImport(byte[] data) throws Exception {
		HSSFWorkbook wb = new HSSFWorkbook(new ByteArrayInputStream(data));
		int s = wb.getNumberOfSheets();
		Collection<ContractClient> clients  = Lists.newArrayList();
		for(int i=0;i<s;i++){
			HSSFSheet sheet = wb.getSheetAt(i);
		    Iterator<Row> rows = sheet.rowIterator();
		    
		    while(rows.hasNext()){
		    	Row row = rows.next();
		      	String cname = ExcelUtil.cellString(row.getCell(0), false);
		      	if(jodd.util.StringUtil.isBlank(cname))continue;
		      	ContractClient client =  getByName(cname);
		        if(client!=null)continue;
		        client = new ContractClient ();
		        client.setName(cname);
		        clients.add(client);
		    }
		    
		}
		
		create(clients);
		return clients;
	}
	
    
	
	
}